<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0" >
    <title>用户注册</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            position: relative; /* 保持与登录页一致：为按钮绝对定位提供全局基准 */
        }

        /* 完全复制登录页的返回按钮样式，确保定位逻辑一致 */
        #resetButtoon {
            background-color: white;
            border: none;
            padding: 10px 20px;
            font-size: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 6px;
            cursor: pointer;
            position: absolute;
            left: 30px;
            top: 10px;
            color: #333;
            width: 96px;
            transition: background-color 0.3s ease;
        }
        #resetButtoon:hover {
            background-color: #f5f7fa;
        }

        .container {
            width: 400px;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            text-align: center;
            /* 移除容器的相对定位：避免按钮相对于容器偏移，与登录页保持一致 */
        }

        h1 {
            color: #333;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 6px;
            color: #555;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 6px;
            box-sizing: border-box;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: #1e66f5;
            box-shadow: 0 0 0 2px rgba(30, 102, 245, 0.1);
        }

        .radio-group {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
        }

        .radio-option {
            display: flex;
            align-items: center;
        }

        .radio-option input {
            margin-right: 5px;
        }

        .invite-code {
            display: none; /* 默认隐藏 */
        }

        .login-link {
            color: #0066ff;
            text-decoration: none;
            font-size: 14px;
            margin-top: 15px;
            display: inline-block;
        }

        .login-link:hover {
            text-decoration: underline;
        }

        button {
            width: 100%;
            padding: 14px;
            background-color: #1e66f5;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
        }

        button:hover {
            background-color: #1952d1;
        }

        /* 错误提示样式 */
        .error-tip {
            color: #ff4d4f;
            font-size: 12px;
            margin-top: 4px;
            height: 16px;
        }

        /* 加载状态样式 */
        button:disabled {
            background-color: #8bb4f8;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
<!-- 按钮位置与登录页完全一致：body内最顶部，不嵌套在任何容器中 -->
<button id="resetButtoon" onclick="goBack()">返回首页</button>

<div class="container">
    <h1>用户注册</h1>

    <form id="registerForm">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" required placeholder="请输入您的用户名" />
            <div class="error-tip" id="usernameError"></div>
        </div>

        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required placeholder="请输入您的密码" />
            <div class="error-tip" id="passwordError"></div>
        </div>

        <div class="form-group invite-code" id="inviteCodeGroup">
            <label for="inviteCode">管理员邀请码（必填）</label>
            <input type="text" id="inviteCode" name="inviteCode" />
            <div class="error-tip" id="inviteCodeError"></div>
        </div>

        <div class="radio-group">
            <div class="radio-option">
                <input type="radio" id="admin" name="role" value="admin" />
                <label for="admin">注册为管理员</label>
            </div>
            <div class="radio-option">
                <input type="radio" id="user" name="role" value="user" />
                <label for="user">注册为用户</label>
            </div>
        </div>

        <p><a href="./login.html" class="login-link">已有账号？去登录</a></p>

        <button type="submit" id="registerBtn">注册</button>
    </form>
</div>

<script>
    // 与登录页完全一致的返回首页逻辑
    function goBack() {
        window.location.href = "home.html";
    }

    // 控制邀请码输入框的显示与隐藏（原有功能不变）
    const adminRadio = document.getElementById('admin');
    const userRadio = document.getElementById('user');
    const inviteCodeGroup = document.getElementById('inviteCodeGroup');

    // 初始化状态：默认选择用户角色
    userRadio.checked = true;
    inviteCodeGroup.style.display = 'none';

    // 监听单选框变化
    adminRadio.addEventListener('change', () => {
        inviteCodeGroup.style.display = adminRadio.checked ? 'block' : 'none';
    });

    userRadio.addEventListener('change', () => {
        inviteCodeGroup.style.display = userRadio.checked ? 'none' : 'block';
    });

    // 表单提交事件（原有功能不变）
    document.getElementById('registerForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        const registerBtn = document.getElementById('registerBtn');
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const inviteCodeInput = document.getElementById('inviteCode');
        const usernameError = document.getElementById('usernameError');
        const passwordError = document.getElementById('passwordError');
        const inviteCodeError = document.getElementById('inviteCodeError');

        // 清空之前的错误提示
        usernameError.textContent = '';
        passwordError.textContent = '';
        inviteCodeError.textContent = '';

        // 获取表单数据
        const username = usernameInput.value.trim();
        const password = passwordInput.value;
        const inviteCode = inviteCodeInput.value.trim();
        const role = document.querySelector('input[name="role"]:checked')?.value;

        // 前端基础验证
        let isValid = true;

        if (!username) {
            usernameError.textContent = '用户名不能为空';
            isValid = false;
        }

        if (!password) {
            passwordError.textContent = '密码不能为空';
            isValid = false;
        }

        // 管理员注册必须填写邀请码
        if (role === 'admin' && !inviteCode) {
            inviteCodeError.textContent = '管理员注册需填写邀请码！';
            isValid = false;
        }

        if (!isValid) {
            return;
        }

        // 准备发送到后端的数据（接口文档中的字段名是userName）
        const formData = {
            userName: username,
            password: password,
            role: role,
            ...(role === 'admin' && { inviteCode: inviteCode })
        };

        // 禁用按钮，防止重复提交
        registerBtn.disabled = true;
        registerBtn.textContent = '注册中...';

        try {
            // 发送注册请求
            const response = await fetch('/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const result = await response.json();

            // 处理API返回结果
            if (response.ok && result.code === 200) {
                alert('注册成功！即将跳转到登录页面');
                window.location.href = './login.html';
            } else {
                // 显示错误信息
                alert(result.message || '注册失败，请稍后重试');
            }
        } catch (error) {
            console.error('注册请求失败:', error);
            alert('网络错误，注册失败，请检查网络连接后重试');
        } finally {
            // 恢复按钮状态
            registerBtn.disabled = false;
            registerBtn.textContent = '注册';
        }
    });

    // 输入框聚焦时清除对应错误提示（原有功能不变）
    document.getElementById('username').addEventListener('focus', function() {
        document.getElementById('usernameError').textContent = '';
    });

    document.getElementById('password').addEventListener('focus', function() {
        document.getElementById('passwordError').textContent = '';
    });

    document.getElementById('inviteCode').addEventListener('focus', function() {
        document.getElementById('inviteCodeError').textContent = '';
    });
</script>
</body>
</html>